<template>
  <view class="download-page">
    <!-- 页面标题栏 -->
    <view class="header">
      <view class="header-title">
        <uni-icons type="download" size="24" color="#007aff"></uni-icons>
        <text class="title">游戏下载管理</text>
      </view>
      <view class="header-actions">
        <button class="clear-btn" @click="clearCompleted" v-if="hasCompletedDownloads">
          清除已完成
        </button>
      </view>
    </view>

    <!-- 下载列表 -->
    <scroll-view class="download-list" scroll-y="true">
      <!-- 进行中的下载 -->
      <view class="section" v-if="activeDownloads.length > 0">
        <view class="section-title">
          <text>正在下载 ({{ activeDownloads.length }})</text>
        </view>
        <view 
          v-for="download in activeDownloads" 
          :key="download.id"
          class="download-item active">
          
          <view class="download-header">
            <view class="game-info">
              <view class="game-icon">🎮</view>
              <view class="game-details">
                <view class="game-name">{{ download.gameName }}</view>
                <view class="game-type">{{ getGameTypeDisplay(download.gameType) }}</view>
              </view>
            </view>
            <view class="download-actions">
              <!-- 暂停按钮 -->
              <button 
                class="pause-btn" 
                @click="pauseDownload(download.id)"
                v-if="download.status === 'downloading'">
                暂停
              </button>
              
              <!-- 取消按钮(清除数据) -->
              <button 
                class="cancel-btn" 
                @click="cancelDownload(download.id)"
                v-if="download.status === 'downloading' || download.status === 'starting' || download.status === 'paused'">
                取消
              </button>
              
              <!-- 继续按钮(从暂停恢复) -->
              <button 
                class="resume-btn" 
                @click="resumeFromPause(download)"
                v-if="download.status === 'paused'">
                继续
              </button>
            </view>
          </view>

          <view class="progress-section">
            <view class="progress-info">
              <text class="progress-text">{{ download.progressText || '0%' }}</text>
              <text class="size-text">{{ download.sizeText || '计算中...' }}</text>
            </view>
            
            <view class="progress-bar-container">
              <view class="progress-bar">
                <view 
                  class="progress-fill" 
                  :style="{ width: (download.progress || 0) + '%' }">
                </view>
              </view>
            </view>
            
            <view class="download-stats">
              <view class="stat-item">
                <text class="stat-label">速度:</text>
                <text class="stat-value">{{ download.speed || '0KB/s' }}</text>
              </view>
              <view class="stat-item">
                <text class="stat-label">剩余:</text>
                <text class="stat-value">{{ download.remainingTime || '计算中...' }}</text>
              </view>
              <view class="stat-item">
                <text class="stat-label">目录:</text>
                <text class="stat-value directory" @click="openDirectory(download.gameType)">
                  {{ getDirectoryDisplayName(download.targetDir, download.gameType) }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 已完成的下载 -->
      <view class="section" v-if="completedDownloads.length > 0">
        <view class="section-title">
          <text>已完成 ({{ completedDownloads.length }})</text>
        </view>
        <view 
          v-for="download in completedDownloads" 
          :key="download.id"
          class="download-item completed">
          
          <view class="download-header">
            <view class="game-info">
              <view class="game-icon">✅</view>
              <view class="game-details">
                <view class="game-name">{{ download.gameName }}</view>
                <view class="game-type">{{ getGameTypeDisplay(download.gameType) }}</view>
              </view>
            </view>
            <view class="download-actions">
              <button 
                class="open-btn" 
                @click="openDirectoryForFile(download)">
                打开目录
              </button>
              <button 
                class="remove-btn" 
                @click="removeDownload(download.id)">
                移除
              </button>
            </view>
          </view>

          <view class="completion-info">
            <text class="completion-time">完成时间: {{ formatTime(download.completedAt) }}</text>
            <text class="file-size">文件大小: {{ download.finalSize || download.sizeText || '未知' }}</text>
            <view class="file-status">
              <text class="file-status-label">状态: </text>
              <text class="file-status-value" :class="{
                'status-success': download.filePath && !download.saveError,
                'status-error': download.saveError,
                'status-pending': !download.filePath && !download.saveError
              }">
                {{ getFileStatusText(download) }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 失败的下载 -->
      <view class="section" v-if="failedDownloads.length > 0">
        <view class="section-title">
          <text>下载失败 ({{ failedDownloads.length }})</text>
        </view>
        <view 
          v-for="download in failedDownloads" 
          :key="download.id"
          class="download-item failed">
          
          <view class="download-header">
            <view class="game-info">
              <view class="game-icon">❌</view>
              <view class="game-details">
                <view class="game-name">{{ download.gameName }}</view>
                <view class="game-type">{{ getGameTypeDisplay(download.gameType) }}</view>
              </view>
            </view>
            <view class="download-actions">
              <button 
                class="resume-btn" 
                @click="resumeDownload(download)"
                v-if="canResume(download)">
                继续下载
              </button>
              <button 
                class="retry-btn" 
                @click="retryDownload(download)"
                v-else>
                重试
              </button>
              <button 
                class="remove-btn" 
                @click="removeDownload(download.id)">
                移除
              </button>
            </view>
          </view>

          <view class="error-info">
            <text class="error-message">{{ download.errorMessage || '下载失败' }}</text>
            <text class="resume-hint" v-if="canResume(download)">检测到断点数据，可继续下载</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="allDownloads.length === 0">
        <view class="empty-icon">📥</view>
        <text class="empty-text">暂无下载任务</text>
        <text class="empty-hint">去聊天页面下载游戏吧！</text>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer" v-if="allDownloads.length > 0">
      <view class="footer-stats">
        <text class="stats-text">
          总计: {{ allDownloads.length }} | 
          进行中: {{ activeDownloads.length }} | 
          已完成: {{ completedDownloads.length }}
        </text>
      </view>
      <view class="footer-actions">
        <button class="clear-all-btn" @click="clearAllDownloads">
          清空所有
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import DownloadManager from '../chat/utils/DownloadManager.js'
import GameDownloadHandler from '../chat/utils/download/GameDownloadHandler.js'

export default {
  name: 'DownloadPage',
  data() {
    return {
      downloads: []
    }
  },
  
  computed: {
    allDownloads() {
      return this.downloads
    },
    
    activeDownloads() {
      return this.downloads.filter(d => 
        d.status === 'downloading' || d.status === 'pending' || d.status === 'starting' || d.status === 'paused'
      )
    },
    
    completedDownloads() {
      return this.downloads.filter(d => d.status === 'completed')
    },
    
    failedDownloads() {
      return this.downloads.filter(d => d.status === 'failed' || d.status === 'error')
    },
    
    hasCompletedDownloads() {
      return this.completedDownloads.length > 0
    }
  },
  
  onLoad() {
    this.loadDownloads()
    this.setupEventListeners()
    this.loadResumableDownloads()
  },
  
  onShow() {
    this.refreshDownloads()
  },
  
  beforeDestroy() {
    this.removeEventListeners()
  },
  
  methods: {
    // 设置事件监听
    setupEventListeners() {
      uni.$on('downloadStart', this.handleDownloadStart)
      uni.$on('downloadProgress', this.handleDownloadProgress)
      uni.$on('downloadComplete', this.handleDownloadComplete)
      uni.$on('downloadError', this.handleDownloadError)
      uni.$on('downloadPaused', this.handleDownloadPaused)
      uni.$on('downloadCancelled', this.handleDownloadCancelled)
      uni.$on('fileSaveSuccess', this.handleFileSaveSuccess)
      uni.$on('fileSaveError', this.handleFileSaveError)
    },
    
    // 移除事件监听
    removeEventListeners() {
      uni.$off('downloadStart', this.handleDownloadStart)
      uni.$off('downloadProgress', this.handleDownloadProgress)
      uni.$off('downloadComplete', this.handleDownloadComplete)
      uni.$off('downloadError', this.handleDownloadError)
      uni.$off('downloadPaused', this.handleDownloadPaused)
      uni.$off('downloadCancelled', this.handleDownloadCancelled)
      uni.$off('fileSaveSuccess', this.handleFileSaveSuccess)
      uni.$off('fileSaveError', this.handleFileSaveError)
    },
    
    // 加载下载列表
    loadDownloads() {
      try {
        const savedDownloads = uni.getStorageSync('activeDownloads') || []
        this.downloads = savedDownloads
      } catch (error) {
        console.log('加载下载列表失败:', error)
        this.downloads = []
      }
    },
    
    // 保存下载列表
    saveDownloads() {
      try {
        uni.setStorageSync('activeDownloads', this.downloads)
      } catch (error) {
        console.log('保存下载列表失败:', error)
      }
    },
    
    // 刷新下载状态
    refreshDownloads() {
      this.loadDownloads()
      this.loadResumableDownloads()
    },
    
    // 加载可恢复的下载
    loadResumableDownloads() {
      try {
        const resumableDownloads = DownloadManager.getAllResumableDownloads()
        console.log('可恢复的下载:', resumableDownloads)
        
        // 为每个可恢复的下载创建或更新下载记录
        resumableDownloads.forEach(resumableInfo => {
          const existingDownload = this.downloads.find(d => 
            d.gameName === resumableInfo.itemName && d.gameType === resumableInfo.gameType
          )
          
          if (!existingDownload) {
            // 创建新的下载记录
            const download = {
              id: resumableInfo.id || Date.now().toString(),
              gameName: resumableInfo.itemName,
              gameType: resumableInfo.gameType,
              status: 'failed',
              progress: resumableInfo.progress || 0,
              progressText: resumableInfo.progress ? `${Math.round(resumableInfo.progress)}%` : '0%',
              sizeText: resumableInfo.totalBytesWritten && resumableInfo.totalBytesExpectedToWrite 
                ? `${this.formatFileSize(resumableInfo.totalBytesWritten)}/${this.formatFileSize(resumableInfo.totalBytesExpectedToWrite)}`
                : '计算中...',
              speed: '0KB/s',
              remainingTime: '已暂停',
              startTime: new Date(resumableInfo.lastUpdate || Date.now()).toISOString(),
              targetDir: resumableInfo.targetDir,
              errorMessage: '下载已中断，可继续下载'
            }
            
            this.downloads.unshift(download)
          } else if (existingDownload.status !== 'completed') {
            // 更新现有记录
            existingDownload.status = 'failed'
            existingDownload.errorMessage = '下载已中断，可继续下载'
          }
        })
        
        this.saveDownloads()
      } catch (error) {
        console.log('加载可恢复下载失败:', error)
      }
    },
    
    // 处理下载开始
    handleDownloadStart(data) {
      const downloadId = Date.now().toString()
      const download = {
        id: downloadId,
        gameName: data.gameName,
        gameType: data.gameType,
        status: 'starting',
        progress: 0,
        progressText: '0%',
        sizeText: '准备中...',
        speed: '0KB/s',
        remainingTime: '计算中...',
        startTime: new Date().toISOString(),
        targetDir: data.targetDir
      }
      
      this.downloads.unshift(download)
      this.saveDownloads()
    },
    
    // 处理下载进度
    handleDownloadProgress(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.gameName && d.gameType === data.gameType && d.status !== 'completed'
      )
      
      if (download) {
        download.status = 'downloading'
        download.progress = data.progress || 0
        download.progressText = data.progressText || '0%'
        download.sizeText = data.sizeText || '计算中...'
        download.speed = this.calculateSpeed(data)
        download.remainingTime = this.calculateRemainingTime(data)
        
        this.saveDownloads()
      }
    },
    
    // 处理下载完成
    handleDownloadComplete(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.gameName && d.gameType === data.gameType && d.status !== 'completed'
      )
      
      if (download) {
        download.status = 'completed'
        download.progress = 100
        download.progressText = '100%'
        download.completedAt = new Date().toISOString()
        // 暂时不设置 filePath，等待 fileSaveSuccess 事件更新最终路径
        // download.filePath = data.filePath // 这是临时路径
        download.finalSize = data.finalSize || download.sizeText
        
        this.saveDownloads()
        
        // 显示完成提示
        uni.showToast({
          title: `《${data.gameName}》下载完成`,
          icon: 'success'
        })
      }
    },
    
    // 处理下载错误
    handleDownloadError(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.gameName && d.gameType === data.gameType && d.status !== 'completed'
      )
      
      if (download) {
        download.status = 'failed'
        download.errorMessage = data.message || '下载失败'
        
        this.saveDownloads()
      }
    },
    
    // 处理下载暂停
    handleDownloadPaused(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.gameName && d.gameType === data.gameType
      )
      
      if (download) {
        download.status = 'paused'
        download.remainingTime = '已暂停'
        this.saveDownloads()
      }
    },
    
    // 处理下载取消
    handleDownloadCancelled(data) {
      const download = this.downloads.find(d => d.id === data.id)
      
      if (download) {
        download.status = 'cancelled'
        this.saveDownloads()
      }
    },
    
    // 处理文件保存成功（更新最终文件路径）
    handleFileSaveSuccess(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.itemName && d.status === 'completed'
      )
      
      if (download) {
        download.filePath = data.filePath
        download.fileName = data.fileName
        this.saveDownloads()
        
        console.log('文件保存成功，更新文件路径:', data.filePath)
      }
    },
    
    // 处理文件保存失败
    handleFileSaveError(data) {
      const download = this.downloads.find(d => 
        d.gameName === data.itemName && d.status === 'completed'
      )
      
      if (download) {
        // 设置为临时文件路径，但标记为保存失败
        download.filePath = data.tempPath
        download.saveError = true
        download.errorMessage = data.error
        this.saveDownloads()
        
        console.log('文件保存失败:', data.error)
      }
    },
    
    // 取消下载
    cancelDownload(downloadId) {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个下载吗？数据将被清除。',
        success: (res) => {
          if (res.confirm) {
            const download = this.downloads.find(d => d.id === downloadId)
            if (download) {
              // 清除断点续传数据
              DownloadManager.clearResumableDownload(download.gameName, download.gameType)
              
              // 发送取消事件给下载核心
              uni.$emit('downloadCancel', { 
                id: downloadId,
                downloadId: downloadId,
                gameName: download.gameName,
                gameType: download.gameType
              })
              
              // 更新本地状态
              download.status = 'cancelled'
              this.saveDownloads()
              
              uni.showToast({
                title: '下载已取消',
                icon: 'success'
              })
            }
          }
        }
      })
    },
    
    // 暂停下载
    pauseDownload(downloadId) {
      const download = this.downloads.find(d => d.id === downloadId)
      if (download) {
        download.status = 'paused'
        download.remainingTime = '已暂停'
        this.saveDownloads()
        
        // 发送暂停事件给下载核心
        uni.$emit('downloadPause', { 
          id: downloadId,
          gameName: download.gameName,
          gameType: download.gameType
        })
      }
    },

    // 从暂停状态继续下载
    resumeFromPause(download) {
      // 尝试使用断点续传功能
      const success = DownloadManager.resumeDownload(download.gameName, download.gameType)
      
      if (success) {
        download.status = 'downloading'
        download.remainingTime = '计算中...'
        this.saveDownloads()
      } else {
        // 如果没有断点数据，提示用户重新下载
        uni.showModal({
          title: '无法继续',
          content: '没有找到断点数据，是否重新开始下载？',
          success: (res) => {
            if (res.confirm) {
              this.retryDownload(download)
            }
          }
        })
      }
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 检查是否可以继续下载
    canResume(download) {
      // 检查是否有断点续传数据
      const resumableInfo = DownloadManager.getResumableDownload(download.gameName, download.gameType)
      return resumableInfo !== null
    },
    
    // 继续下载
    resumeDownload(download) {
      const success = DownloadManager.resumeDownload(download.gameName, download.gameType)
      if (success) {
        // 更新UI状态
        download.status = 'downloading'
        this.saveDownloads()
      }
    },
    
    // 重试下载
    retryDownload(download) {
      uni.showModal({
        title: '重新下载',
        content: '将重新开始下载，是否继续？',
        success: (res) => {
          if (res.confirm) {
            // 清除旧的断点数据
            DownloadManager.clearResumableDownload(download.gameName, download.gameType)
            
            // 移除当前下载记录
            this.removeDownload(download.id)
            
            uni.showToast({
              title: '请重新选择下载方式',
              icon: 'none'
            })
            
            // 返回聊天页面重新下载
            uni.navigateBack()
          }
        }
      })
    },
    
    // 移除下载记录
    removeDownload(downloadId) {
      const index = this.downloads.findIndex(d => d.id === downloadId)
      if (index > -1) {
        this.downloads.splice(index, 1)
        this.saveDownloads()
      }
    },
    
    // 打开文件所在目录
    openDirectoryForFile(download) {
      if (!download.filePath) {
        uni.showToast({
          title: '文件路径无效',
          icon: 'error'
        })
        return
      }
      
      // 获取文件所在目录
      const fileDirectory = GameDownloadHandler.getGameFileDirectory(download.gameType, download.filePath)
      
      // 打开目录
      this.openSpecificDirectory(fileDirectory, download.gameType)
    },
    
    // 打开目录
    openDirectory(gameType) {
      DownloadManager.openGameDirectory(gameType, null)
    },
    
    // 打开指定目录
    openSpecificDirectory(directoryPath, gameType) {
      DownloadManager.openGameDirectory(gameType, null, directoryPath)
    },
    
    // 清除已完成的下载
    clearCompleted() {
      uni.showModal({
        title: '确认清除',
        content: '确定要清除所有已完成的下载记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.downloads = this.downloads.filter(d => d.status !== 'completed')
            this.saveDownloads()
          }
        }
      })
    },
    
    // 清空所有下载
    clearAllDownloads() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有下载记录吗？正在进行的下载也会被取消。',
        success: (res) => {
          if (res.confirm) {
            // 取消所有进行中的下载
            this.activeDownloads.forEach(download => {
              uni.$emit('downloadCancel', { 
                id: download.id,
                downloadId: download.id,
                gameName: download.gameName,
                gameType: download.gameType
              })
              
              // 清除断点数据
              DownloadManager.clearResumableDownload(download.gameName, download.gameType)
            })
            
            this.downloads = []
            this.saveDownloads()
          }
        }
      })
    },
    
    // 计算下载速度
    calculateSpeed(data) {
      if (data.bytesWritten && data.startTime) {
        const now = Date.now()
        const elapsed = (now - data.startTime) / 1000 // 秒
        if (elapsed > 0) {
          const speed = data.bytesWritten / elapsed
          return this.formatSpeed(speed)
        }
      }
      return '计算中...'
    },
    
    // 计算剩余时间
    calculateRemainingTime(data) {
      if (data.bytesWritten && data.totalBytes && data.startTime) {
        const now = Date.now()
        const elapsed = (now - data.startTime) / 1000
        if (elapsed > 0) {
          const speed = data.bytesWritten / elapsed
          const remaining = (data.totalBytes - data.bytesWritten) / speed
          return this.formatTime(remaining)
        }
      }
      return '计算中...'
    },
    
    // 格式化速度
    formatSpeed(bytesPerSecond) {
      if (bytesPerSecond === 0) return '0B/s'
      const k = 1024
      const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s']
      const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k))
      return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
    },
    
    // 格式化时间
    formatTime(seconds) {
      if (seconds <= 0 || !isFinite(seconds)) return '计算中...'
      
      if (typeof seconds === 'string') {
        return seconds
      }
      
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = Math.floor(seconds % 60)
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      } else if (minutes > 0) {
        return `${minutes}分${secs}秒`
      } else {
        return `${secs}秒`
      }
    },
    
    // 获取游戏类型显示
    getGameTypeDisplay(type) {
      if (!type) return ''
      
      const gameTypes = {
        'gba': 'GBA游戏',
        'psp': 'PSP游戏', 
        'exe': 'PC游戏',
        'apk': 'Android游戏',
        'ipa': 'iOS游戏',
        'nds': 'NDS游戏',
        'ps1': 'PS1游戏',
        'ps2': 'PS2游戏',
        'n64': 'N64游戏',
        'snes': 'SNES游戏',
        'nes': 'FC游戏',
        'gbc': 'GBC游戏',
        'gb': 'GB游戏',
        'md': 'MD游戏',
        'arcade': '街机游戏',
        'steam': 'Steam游戏',
        'switch': 'Switch游戏',
        'ps3': 'PS3游戏',
        'ps4': 'PS4游戏',
        'ps5': 'PS5游戏',
        'xbox': 'Xbox游戏',
        'wii': 'Wii游戏',
        '3ds': '3DS游戏'
      }
      
      return gameTypes[type.toLowerCase()] || type.toUpperCase()
    },
    
    // 获取游戏目录
    getGameDirectory(gameType) {
      const baseDir = '/Games'
      
      const typeDirs = {
        'gba': `${baseDir}/GBA`,
        'psp': `${baseDir}/PSP`,
        'exe': `${baseDir}/PC`,
        'apk': `${baseDir}/Android`,
        'ipa': `${baseDir}/iOS`,
        'nds': `${baseDir}/NDS`,
        'ps1': `${baseDir}/PlayStation1`,
        'ps2': `${baseDir}/PlayStation2`,
        'ps3': `${baseDir}/PlayStation3`,
        'ps4': `${baseDir}/PlayStation4`,
        'ps5': `${baseDir}/PlayStation5`,
        'xbox': `${baseDir}/Xbox`,
        'wii': `${baseDir}/Wii`,
        'switch': `${baseDir}/Switch`,
        'n64': `${baseDir}/Nintendo64`,
        'snes': `${baseDir}/SNES`,
        'nes': `${baseDir}/NES`,
        'gbc': `${baseDir}/GameBoyColor`,
        'gb': `${baseDir}/GameBoy`,
        'md': `${baseDir}/MegaDrive`,
        'arcade': `${baseDir}/Arcade`,
        'steam': `${baseDir}/Steam`,
        '3ds': `${baseDir}/3DS`
      }
      
      return typeDirs[gameType] || `${baseDir}/Other`
    },
    
    // 获取目录显示名称
    getDirectoryDisplayName(targetDir, gameType) {
      if (!targetDir || targetDir === '默认目录') {
        return this.getGameDirectory(gameType)
      }
      
      // 如果是自定义目录路径，尝试显示友好名称
      if (targetDir.startsWith('/')) {
        try {
          const directories = uni.getStorageSync('customDownloadDirectories') || []
          const customDir = directories.find(dir => dir.path === targetDir)
          if (customDir) {
            return `${customDir.name} (${targetDir})`
          }
        } catch (error) {
          console.log('获取自定义目录失败:', error)
        }
        return targetDir
      }
      
      return targetDir
    },
    
    // 获取文件状态文本
    getFileStatusText(download) {
      if (download.saveError) {
        return '保存失败'
      } else if (download.filePath) {
        return '保存成功'
      } else {
        return '处理中...'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.download-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  background-color: white;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-left: 8px;
}

.clear-btn {
  background-color: #ff3b30;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.download-list {
  flex: 1;
  padding: 0 16px;
}

.section {
  margin: 16px 0;
}

.section-title {
  padding: 8px 0;
  border-bottom: 2px solid #007aff;
  margin-bottom: 12px;
  
  text {
    font-size: 16px;
    font-weight: 600;
    color: #007aff;
  }
}

.download-item {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.download-item.active {
  border-left: 4px solid #007aff;
}

.download-item.completed {
  border-left: 4px solid #34c759;
}

.download-item.failed {
  border-left: 4px solid #ff3b30;
}

.download-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.game-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.game-icon {
  font-size: 24px;
  margin-right: 12px;
}

.game-details {
  flex: 1;
}

.game-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.game-type {
  font-size: 12px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.download-actions {
  display: flex;
  gap: 8px;
}

.cancel-btn, .pause-btn, .resume-btn, .open-btn, .retry-btn, .remove-btn {
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.cancel-btn {
  background-color: #ff3b30;
  color: white;
}

.pause-btn {
  background-color: #ff9500;
  color: white;
}

.resume-btn {
  background-color: #34c759;
  color: white;
}

.open-btn {
  background-color: #007aff;
  color: white;
}

.retry-btn {
  background-color: #ff9500;
  color: white;
}

.remove-btn {
  background-color: #8e8e93;
  color: white;
}

.progress-section {
  margin-bottom: 8px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.progress-text {
  font-size: 16px;
  font-weight: 600;
  color: #007aff;
}

.size-text {
  font-size: 14px;
  color: #666;
}

.progress-bar-container {
  margin-bottom: 12px;
}

.progress-bar {
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #007aff 0%, #00d4ff 100%);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.download-stats {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.stat-value {
  font-size: 12px;
  color: #333;
  font-weight: 500;
}

.stat-value.directory {
  color: #007aff;
  text-decoration: underline;
}

.completion-info, .error-info {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.completion-time, .file-size {
  font-size: 12px;
  color: #666;
  display: block;
  margin-bottom: 4px;
}

.file-status {
  display: flex;
  align-items: center;
  margin-top: 4px;
}

.file-status-label {
  font-size: 12px;
  color: #666;
}

.file-status-value {
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  color: #34c759;
}

.status-error {
  color: #ff3b30;
}

.status-pending {
  color: #ff9500;
}

.error-message {
  font-size: 12px;
  color: #ff3b30;
  display: block;
  margin-bottom: 4px;
}

.resume-hint {
  font-size: 11px;
  color: #34c759;
  display: block;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: #666;
  display: block;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  display: block;
}

.footer {
  background-color: white;
  padding: 12px 16px;
  border-top: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stats-text {
  font-size: 12px;
  color: #666;
}

.clear-all-btn {
  background-color: #ff3b30;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}
</style>